package com.heatup.apt.api.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.heatup.apt.api.controller.MyBookController;
import com.heatup.apt.api.controller.pay.TenWeChatGenerator;
import com.heatup.apt.api.controller.pay.util.PropertiesUtil;
import com.heatup.apt.api.service.AccessService;
import com.heatup.apt.api.service.CourseSignService;
import com.heatup.apt.api.service.MyBooksService;
import com.heatup.apt.common.constants.CourseConstants.CourseType;
import com.heatup.apt.common.constants.OrderContants;
import com.heatup.apt.common.constants.OrderContants.OrderStatus;
import com.heatup.apt.common.constants.ServiceConstans.ServiceType;
import com.heatup.apt.common.dao.*;
import com.heatup.apt.common.dao.coach.CoachInfoMapper;
import com.heatup.apt.common.dao.redis.TokenRedisDao;
import com.heatup.apt.common.dao.store.StoreInfoMapper;
import com.heatup.apt.common.exception.OrderNotFoundException;
import com.heatup.apt.common.util.DateUtil;
import com.heatup.apt.common.util.DateUtils;
import com.heatup.apt.model.Resource;
import com.heatup.apt.model.ResourceExample;
import com.heatup.apt.model.api.ApiResultModel;
import com.heatup.apt.model.coach.CoachInfo;
import com.heatup.apt.model.course.CourseInfo;
import com.heatup.apt.model.course.CourseSchedule;
import com.heatup.apt.model.course.CourseStore;
import com.heatup.apt.model.course.CourseTime;
import com.heatup.apt.model.order.OrderDetail;
import com.heatup.apt.model.order.OrderInfo;
import com.heatup.apt.model.order.PrivateConsultOrderApiModel;
import com.heatup.apt.model.product.ServicePrice;
import com.heatup.apt.model.store.StoreInfo;
import com.heatup.apt.model.weixin.Token;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by b3st9u on 16/8/30.
 */
@Service
public class MyBookServiceImpl implements MyBooksService {
	@Autowired
	private OrderDetailMapper orderDetailMapper;
	@Autowired
	private OrderInfoMapper orderInfoMapper;
	@Autowired
	private CourseInfoMapper courseInfoMapper;
	@Autowired
	private CoachInfoMapper coachInfoMapper;
	@Autowired
	private StoreInfoMapper storeInfoMapper;
	@Autowired
	private CourseScheduleMapper courseScheduleMapper;
	@Autowired
	private ServicePriceMapper servicePriceMapper;
	@Autowired
	private ResourceMapper resourceMapper;
	@Autowired
	private TokenRedisDao tokenRedisDao;
	@Autowired
	private CourseStoreMapper courseStoreMapper;
	@Autowired
	private AccessService accessService;
	@Autowired
	private CourseSignMapper  courseSignMapper;

	private static final Logger logger = LoggerFactory.getLogger(MyBookController.class);

	/**
	 * 获取我的团课预定
	 *
	 * @param bookStatus
	 * @return
	 */
	public List<Map<String, Object>> getMyTeamCoureseBooks(int bookStatus, List<OrderInfo> orderList) throws OrderNotFoundException {
		List<Map<String, Object>> myBooks = Lists.newArrayList();
		for (OrderInfo orderInfo : orderList) {
			Integer serviceId = orderInfo.getServiceId();
			ServicePrice servicePrice = servicePriceMapper.selectByPrimaryKey(serviceId);
			int courseId = servicePrice.getCourseId();
			CourseInfo courseInfo = courseInfoMapper.selectById(courseId);
			int storeId = servicePrice.getStoreId();
			StoreInfo storeInfo = storeInfoMapper.selectById(storeId);
			CoachInfo coachInfo = coachInfoMapper.selectCoachInfoByCourseId(1, courseId);

            CourseSchedule courseScheduleDB = new CourseSchedule();
            courseScheduleDB.setCourseId(courseId);
            EntityWrapper<CourseSchedule> entityWrapper = new EntityWrapper<>(courseScheduleDB);
            List<CourseSchedule> scheduleList = courseScheduleMapper.selectList(entityWrapper);

			CourseSchedule courseSchedule = null;

			if (scheduleList.size() > 0) {
				courseSchedule = scheduleList.get(0);
			}

			Map<String, Object> map = new HashMap<>();
			map.put("title", courseInfo.getTitle());
			map.put("coachchName", coachInfo.getNickName());
			map.put("courseId", courseInfo.getId());
			map.put("orderId", orderInfo.getId());
            map.put("orderNumber", orderInfo.getOrderNumber());
            map.put("payType",orderInfo.getPayType() == 2 ? 2 : 1);
			// 门店
			if (storeInfo != null) {
				map.put("storeId", String.valueOf(storeId));
				map.put("storeName", storeInfo.getStoreName());
				map.put("storeAddress", storeInfo.getAddress());
			}

			// 教练
			if (coachInfo != null) {
				map.put("coachName", coachInfo.getNickName());
				map.put("coachHeadImg", coachInfo.getHeadImg());
			}

			// 课程时长
			if (courseSchedule != null) {
				map.put("duration", courseSchedule.getDuration());
			}

			// 正常
			if (bookStatus == OrderStatus.NORMAL.getIndex()) {

				Date now = new Date();

				map.putAll( accessService.updateAndGetNewQRCodeByOrderId( orderInfo.getId()));//门禁二维码


				try {
					map.put("countdown", daysBetween(now, courseSchedule.getStartTime()));
				} catch (ParseException e) {
					e.printStackTrace();
				}
				Date startTime = courseSchedule.getStartTime();
				Date endTime = courseSchedule.getEndTime();
				String time = "";

//				// 已过
				if (endTime.before(new Date())) {
					continue;
				}

				if (DateUtil.isToday(startTime)) {
					time = "今天 " + DateUtils.format(startTime, DateUtils.shortTimePattern);
				} else {
					time = DateUtils.format(startTime, DateUtils.datePattern) + "|"
							+ DateUtils.format(startTime, DateUtils.shortTimePattern);
				}
				map.put("startTime", time);
			}

			// 预约排队
			if (bookStatus == OrderStatus.WAIT.getIndex()) {
				int waitCount = orderInfoMapper.queryBeforeWaitNum(orderInfo.getId(), orderInfo.getServiceId());
				map.put("waitCount", courseInfo.getWaitCount());
				// todo:提交排队订单时生成

				if(OrderContants.OrderStatus.WAIT.getStatus().equals(orderInfo.getOrderStatus())){
					map.put("myWaitNumber", waitCount+1);
				}else{
					map.put("myWaitNumber", 0);
				}


				Date startTime = courseSchedule.getStartTime();
				Date endTime = DateUtil.addMinites(startTime, courseSchedule.getDuration());
				String time = DateUtils.format(startTime, DateUtils.shortDatePattern) + " "
						+ DateUtils.format(startTime, DateUtils.shortTimePattern) + "～"
						+ DateUtils.format(endTime, DateUtils.shortTimePattern);
				map.put("startTime", time);
			}

			// 已完成
			if (bookStatus == OrderStatus.FINISH.getIndex()) {
				Date startTime = courseSchedule.getStartTime();
				Date endTime = DateUtil.addMinites(startTime, courseSchedule.getDuration());
				String time = DateUtils.format(startTime, DateUtils.shortDatePattern) + " "
						+ DateUtils.format(startTime, DateUtils.shortTimePattern) + "～"
						+ DateUtils.format(endTime, DateUtils.shortTimePattern);
				map.put("startTime", time);
			}

			// 已取消
			if (bookStatus == OrderStatus.FINISH.getIndex()) {
				Date startTime = courseSchedule.getStartTime();
				Date endTime = DateUtil.addMinites(startTime, courseSchedule.getDuration());
				String time = DateUtils.format(startTime, DateUtils.shortDatePattern) + " "
						+ DateUtils.format(startTime, DateUtils.shortTimePattern) + "～"
						+ DateUtils.format(endTime, DateUtils.shortTimePattern);
				map.put("startTime", time);
			}

			myBooks.add(map);
		}
		return myBooks;
	}

	/**
	 * 获取自助健身预定 获取自助健身订单列表
	 * 
	 * @param bookStatus
	 * @return
	 */
	public List<Map<String, Object>> getSelffitnessBooks(int bookStatus, List<OrderInfo> orderList) throws OrderNotFoundException {
		List<Map<String, Object>> mybooks = Lists.newArrayList();
		for (OrderInfo orderInfo : orderList) {
			Integer serviceId = orderInfo.getServiceId();
			ServicePrice servicePrice = servicePriceMapper.selectByPrimaryKey(serviceId);
			int storeId = servicePrice.getStoreId();

			StoreInfo storeInfo = storeInfoMapper.selectById(storeId);
			OrderDetail orderDetail = orderDetailMapper.queryOrderDetailByOrderId(orderInfo.getId());;
			Map<String, Object> map = new HashMap<>();
			int duration = 0;
			if (orderDetail != null) {
				// 时长
				map.put("duration", orderDetail.getDuration());
				duration = orderDetail.getDuration();
				map.put("countdown", orderDetail.getStartTime());
			}

			map.put("orderId", orderInfo.getId());
            map.put("orderNumber", orderInfo.getOrderNumber());
            map.put("title", servicePrice.getServiceName());
			map.put("payType",orderInfo.getPayType() == 2 ? 2 : 1);
			// 门店
			if (storeInfo != null) {
				map.put("storeId", String.valueOf(storeId));
				map.put("storeName", storeInfo.getStoreName());
				map.put("storeAddress", storeInfo.getAddress());
			}

			// 正常
			if (bookStatus == OrderStatus.NORMAL.getIndex()) {


				map.putAll( accessService.updateAndGetNewQRCodeByOrderId( orderInfo.getId()));//门禁二维码

				Date startTime = orderDetail.getStartTime();
				Date endTime = DateUtils.addMinutes(orderDetail.getStartTime(),orderDetail.getDuration());
				String time = "";

				// 已过
				if (endTime.before(new Date())) {
					continue;
				}

				if (DateUtil.isToday(startTime)) {
					time = "今天 " + DateUtils.format(startTime, DateUtils.shortTimePattern);
				} else {
					time = DateUtils.format(startTime, DateUtils.datePattern) + "|"
							+ DateUtils.format(startTime, DateUtils.shortTimePattern);
				}
				map.put("startTime", time);
			}

			// 已完成
			if (bookStatus == OrderStatus.FINISH.getIndex()) {
				Date startTime = orderDetail.getStartTime();
				Date endTime = DateUtil.addMinites(startTime, duration);
				String time = DateUtils.format(startTime, DateUtils.shortDatePattern) + " "
						+ DateUtils.format(startTime, DateUtils.shortTimePattern) + "～"
						+ DateUtils.format(endTime, DateUtils.shortTimePattern);
				map.put("startTime", time);
			}

			// 已取消
			if (bookStatus == OrderStatus.FINISH.getIndex()) {
				Date startTime = orderDetail.getStartTime();
				Date endTime = DateUtil.addMinites(startTime, duration);
				String time = DateUtils.format(startTime, DateUtils.shortDatePattern) + " "
						+ DateUtils.format(startTime, DateUtils.shortTimePattern) + "～"
						+ DateUtils.format(endTime, DateUtils.shortTimePattern);
				map.put("startTime", time);
			}

			mybooks.add(map);
		}
		return mybooks;
	}

    /**
     * 课程列表(檬营/私教/团课/自助健身)
     * @param bookStatus
     * @param serviceType
     * @param userId
     * @param campType 檬营专用 1未成营排队 2爆仓排队
     * @return
     */
	@Override
	public List<Map<String, Object>> getMyBooks(int bookStatus, int serviceType, int userId, Integer campType) throws OrderNotFoundException {

        // 查询用户订单
        List<OrderInfo> orderList = null;
        // 已完成和已取消不区分类型
        if (bookStatus == OrderStatus.CANCEL.getIndex()) {
        	
            orderList = orderInfoMapper.queryUserCancelledOrderByUserId(userId);
        }else if(bookStatus == OrderStatus.FINISH.getIndex()){
        	orderList = orderInfoMapper.queryOrderInfoBySelfFitness(userId);
        }else if(serviceType == OrderContants.OrderType.fun_camp.getIndex() && userId > 0 && campType == null) {
            //我的预约-预定成功 檬营订单列表 blank
            orderList = orderInfoMapper.queryCampCourseOrderList(userId, null);
        }else if(bookStatus == 3 && serviceType == OrderContants.OrderType.fun_camp.getIndex() && userId > 0 && campType!=null && campType.intValue() >0){
            //我的檬营未成营/爆仓排队列表
            orderList = orderInfoMapper.queryCampCourseOrderList(userId,campType);

        }else if(serviceType == OrderContants.OrderType.pt.getIndex() && userId > 0
        		|| serviceType == OrderContants.OrderType.physical_examination.getIndex() && userId > 0
        		|| serviceType == OrderContants.OrderType.secret_experience.getIndex() && userId > 0) {
            //我的预约-即将开始 私教订单列表
            orderList = orderInfoMapper.querySecretCourseOrderList(userId, 1);
        }else if(serviceType == OrderContants.OrderType.team_course.getIndex() && userId>0){
        	//我的预约-即将开始 团课订单列表
        	orderList = orderInfoMapper.queryMyBookTeamCourseBy(userId, String.valueOf(bookStatus), serviceType);
        }else if(serviceType == OrderContants.OrderType.selffit.getIndex() && userId>0){
        	orderList = orderInfoMapper.queryMyBookSelffitBy(userId,  String.valueOf(bookStatus), serviceType);
        }else if(serviceType == OrderContants.OrderType.private_bespeak.getIndex() && userId > 0){
        	// 私教预约订单
        	return orderInfoMapper.queryPrivateBespeakByUserId(userId);
        }
        else {
           
		    orderList = orderInfoMapper.queryUserPaymentNotFinishOrder(userId, bookStatus, serviceType);
		}

		if (orderList == null || orderList.size() <= 0) {
			return null;
		}

		// 已完成和已取消
		if (bookStatus == OrderStatus.CANCEL.getIndex() || bookStatus == OrderStatus.FINISH.getIndex()) {
			/*return getMyFinishOrCancelBooks(bookStatus, orderList);*/
			
			return getMyFinishOrCancelBooksNew(bookStatus, orderList);
		}

		// 团课
		if (serviceType == ServiceType.teamCourse.getIndex()) {
			return getMyTeamCoureseBooks(bookStatus, orderList);
		}

		// 自助健身
		if (serviceType == ServiceType.selfFitness.getIndex()) {
			return getSelffitnessBooks(bookStatus, orderList);
		}

		// 私课
		if (serviceType == ServiceType.privateCourse.getIndex()) {
			return getMyPrivateCoureseBooks(bookStatus, orderList);
		}

		// 檬营
		if (serviceType == ServiceType.campCourse.getIndex()) {
			return getMyCampCoureseBooks(bookStatus, orderList);
		}

		// old code
		List<Map<String, Object>> mybooks = Lists.newArrayList();
		return mybooks;
	}

	@Override
	public Map<String, Object> getMyBookDetail(int orderId, int userId) throws OrderNotFoundException {
		Map<String, Object> map = new HashMap<String, Object>();
		OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
		if (orderInfo != null) {
			ServicePrice servicePrice = servicePriceMapper.selectByPrimaryKey(orderInfo.getServiceId());
			int courseId = 0;

			if (orderInfo.getOrderType() != 4 && orderInfo.getOrderType() != 5) {
				if (servicePrice != null) {
					courseId = servicePrice.getCourseId();
				}
				CourseInfo courseInfo = courseInfoMapper.selectById(courseId);

				// 获取课程标题
				if (courseInfo != null) {
					map.put("title", courseInfo.getTitle());
					map.put("introduce", courseInfo.getIntroduce());
					map.put("course_headImg", courseInfo.getHeadImg());
					map.put("courseId", courseInfo.getId());

				}

                CourseSchedule courseScheduleDB = new CourseSchedule();
                courseScheduleDB.setCourseId(courseInfo.getId());
                EntityWrapper<CourseSchedule> entityWrapper = new EntityWrapper<>(courseScheduleDB);
                List<CourseSchedule> courseSchedules = courseScheduleMapper.selectList(entityWrapper);

				String courseTime = "待与教练沟通确认";
				String sectionTime = "";
				if (courseSchedules != null && courseSchedules.size() > 0) {
					CourseSchedule courseSchedule = courseSchedules.get(0);
					Date startTime = courseSchedule.getStartTime();
					Date endTime = DateUtil.addMinites(startTime, courseSchedule.getDuration());
					courseTime = DateUtils.format(startTime, DateUtils.datePatternAllHH);
					sectionTime = DateUtils.format(startTime, DateUtils.datePattern) + " "
							+ DateUtils.format(startTime, DateUtils.shortTimePattern) + "～"
							+ DateUtils.format(endTime, DateUtils.shortTimePattern);
				}
				map.put("startTime", courseTime);
				map.put("sectionTime", sectionTime);
				CoachInfo coachInfo = coachInfoMapper.selectCoachInfoByCourseId(1, courseInfo.getId());// 获取主教练
				if (coachInfo != null) {
					map.put("coachName", coachInfo.getNickName());
					map.put("headImg", coachInfo.getHeadImg());
				}

			}
			List<StoreInfo> storeInfos = storeInfoMapper.selectByCourseId(courseId);
			if (storeInfos != null && storeInfos.size() > 0) {
				StringBuffer storeNamesb = new StringBuffer();
				for (StoreInfo storeInfo : storeInfos) {
					storeNamesb.append(storeInfo.getStoreName()).append(";");
				}
				map.put("storeName", storeNamesb);

				if (storeInfos.size() == 1) {
					map.put("address", storeInfos.get(0).getAddress());
					map.put("addressLink", storeInfos.get(0).getAddressLink());
					map.put("notice", storeInfos.get(0).getNotice().split("\r\n"));
					map.put("storeId", storeInfos.get(0).getId());
					map.put("store_venues", storeInfos.get(0).getVenues());
				}
			}
			
			OrderDetail orderDetail = orderDetailMapper.queryOrderDetailByOrderId(orderInfo.getId());

			if (orderDetail != null) {
				if (orderInfo.getOrderType() == 4) {
					StoreInfo storeInfo = storeInfoMapper.selectById(orderDetail.getStoreId());
					map.put("address", storeInfo.getAddress());
					map.put("notice", Arrays.asList(storeInfo.getNotice().split("\r\n")));
					map.put("notice", storeInfo.getNotice().split("\r\n"));
					map.put("longitude", storeInfo.getLongitude());
					map.put("latitude", storeInfo.getLatitude());
					map.put("storeId", storeInfo.getId());
					map.put("store_venues", storeInfo.getVenues());
					String sectionTime = getDateType(orderDetail.getStartTime(), orderDetail.getDuration(), "");

					map.put("sectionTime", sectionTime);
				}
			}
			// 订单信息
			if (orderInfo != null) {
				int orderIds = orderInfo.getId();
				map.put("orderStatus", orderInfo.getOrderStatus());
				map.put("totalPrice", orderInfo.getAmount());
				map.put("payStatus", orderInfo.getPayStatus());
				map.put("orderStatus", orderInfo.getOrderStatus());
				Map<Object, Object> params = new HashMap<>();
				params.put("orderIds", orderIds);
				params.put("courseId", courseId);
				params.put("orderType", orderInfo.getOrderType());
				if (orderInfo.getOrderType() == 1) {
					map.put("orderStatuAll", orderInfoMapper.getOrderStatusAll(params));
					map.put("orderStatuNum", orderInfoMapper.getOrderStatusNumber(params));
				} else {
					map.put("orderStatuAll", 0);
					map.put("orderStatuNum", 0);
				}

			}
			map.put("payType",orderInfo.getPayType() == 2 ? 2 : 1);
			map.put("personCount", orderDetail.getPersonCount());
			map.putAll( accessService.updateAndGetNewQRCodeByOrderId( orderInfo.getId()));//门禁二维码
			map.put("countdown", "10");

		}

		return map;
	}

    /**
     * 我的预约 即将开始/未成营列表-檬营列表
     * @param bookStatus
     * @param orderList
     * @return
     */
	public List<Map<String, Object>> getMyCampCoureseBooks(int bookStatus, List<OrderInfo> orderList) throws OrderNotFoundException {
		List<Map<String, Object>> mybooks = Lists.newArrayList();
		for (OrderInfo orderInfo : orderList) {
			Integer serviceId = orderInfo.getServiceId();
			ServicePrice servicePrice = servicePriceMapper.selectByPrimaryKey(serviceId);
			int courseId = servicePrice.getCourseId();
			Map<String, Object> map = new HashMap<>();

			// 课程
			CourseInfo courseInfo = courseInfoMapper.selectById(courseId);
			map.put("courseSchedule", courseInfo.getStartEndTime());
			String storeNames = "";
			// 门店
			List<StoreInfo> storeList = storeInfoMapper.selectByCourseId(courseId);
			StringBuffer storeName = new StringBuffer();
			if (storeList != null) {
				for (StoreInfo storeInfo : storeList) {
					storeName.append(storeInfo.getStoreName()).append(";");
				}
				storeNames = storeName.substring(0, storeName.length() - 1);
				map.put("storeName", storeNames);
			}
			// 教练
			CoachInfo coachInfo = coachInfoMapper.selectCoachInfoByCourseId(1, courseId);

			map.put("orderId", orderInfo.getId());
			map.put("orderNumber", orderInfo.getOrderNumber());
			map.put("payType",orderInfo.getPayType() == 2 ? 2 : 1);
			if (courseInfo != null) {
				map.put("title", courseInfo.getTitle());
				map.put("courseId", courseInfo.getId());
			}
			if (coachInfo != null) {
				map.put("coachName", coachInfo.getNickName());
				map.put("coachHeadImg", coachInfo.getHeadImg());
				map.put("coachMobile", coachInfo.getMobile());
				map.put("coachId", coachInfo.getId());
			}
			// 正常
			if (bookStatus == OrderStatus.NORMAL.getIndex()) {
				map.put("orderId", orderInfo.getId());
				map.put("periods", courseInfo.getPeriods());// 课时
				map.put("finishPeridos", 0);// TODO已完成课时
			}

			map.putAll(accessService.updateAndGetNewQRCodeByOrderId(orderInfo.getId()));//门禁二维码


			// 预约排队
			if (bookStatus == OrderStatus.WAIT.getIndex()) {
				if (courseInfo != null) {
					map.put("maxCount", courseInfo.getMaxCount());
					map.put("minCount", courseInfo.getMinCount());
					map.put("currentCount", courseInfo.getCurrentCount());
					int waitCount = orderInfoMapper.queryBeforeWaitNum(orderInfo.getId(), orderInfo.getServiceId());
					map.put("waitCount", courseInfo.getWaitCount());

					if(OrderContants.OrderStatus.WAIT.getStatus().equals(orderInfo.getOrderStatus())){
						map.put("myWaitNumber", waitCount+1);
					}else{
						map.put("myWaitNumber", 0);
					}
					
					map.put("periods", courseInfo.getPeriods());// 课时
					map.put("deadline", DateUtil.formatDate(courseInfo.getDeadline(), DateUtil.FMT_DATE_YYYYMMDD_HHMMSS));// 截止时间
					map.put("countdown", DateUtils.betweenSeconds(courseInfo.getDeadline()));// 截止时间倒计时秒数
				}
				map.put("storeName", storeNames);
				map.put("orderId", orderInfo.getId());
			}
			mybooks.add(map);
		}
		return mybooks;
	}

	public List<Map<String, Object>> getMyPrivateCoureseBooks(int bookStatus, List<OrderInfo> orderList) {
		List<Map<String, Object>> mybooks = Lists.newArrayList();
		for (OrderInfo orderInfo : orderList) {
			Integer serviceId = orderInfo.getServiceId();
			ServicePrice servicePrice = servicePriceMapper.selectByPrimaryKey(serviceId);
			OrderDetail orderDetail = orderDetailMapper.queryOrderDetailByOrderId(orderInfo.getId());
			int courseId = 0;
			if (servicePrice != null) {
				courseId = servicePrice.getCourseId();
			}
			Map<String, Object> map = new HashMap<String, Object>();
			
            CourseSchedule courseScheduleDB = new CourseSchedule();
            courseScheduleDB.setCourseId(courseId);
            EntityWrapper<CourseSchedule> entityWrapper = new EntityWrapper<>(courseScheduleDB);
            List<CourseSchedule> courseScheduleList = courseScheduleMapper.selectList(entityWrapper);
			String courseTime = "待与教练沟通确认";
			String time = "";
			if (courseScheduleList != null && courseScheduleList.size() > 0) {
				CourseSchedule courseSchedule = courseScheduleList.get(0);// 取最近的一个schedule
				courseTime = DateUtil.formatDate(courseSchedule.getStartTime(), DateUtil.FMT_DATE_YYYYMMDD_HHMMSS) + "~"
						+ DateUtil.formatDate(courseSchedule.getEndTime(), DateUtil.FMT_DATE_YYYYMMDD_HHMMSS);
				Date startTime = courseSchedule.getStartTime();
				Date endTime = DateUtil.addMinites(startTime, courseSchedule.getDuration());

				time = DateUtils.format(startTime, DateUtils.shortDatePattern) + " "
						+ DateUtils.format(startTime, DateUtils.shortTimePattern) + "～"
						+ DateUtils.format(endTime, DateUtils.shortTimePattern);
			}
			// 课程
			CourseInfo courseInfo = courseInfoMapper.selectById(courseId);

			// 门店
			List<StoreInfo> storeInfos = storeInfoMapper.selectByCourseId(courseId);
			StringBuffer storeNamesb = new StringBuffer();
			if (storeInfos != null) {
				for (StoreInfo storeInfo : storeInfos) {
					storeNamesb.append(storeInfo.getStoreName()).append(";");
					
				}

			}
			// 教练
			CoachInfo coachInfo = null;
			if(orderInfo.getOrderType().intValue() == OrderContants.OrderType.physical_examination.getIndex()
					|| orderInfo.getOrderType().intValue() == OrderContants.OrderType.secret_experience.getIndex()){
				coachInfo = coachInfoMapper.selectById(orderDetail.getCoachId());
			}else{
				coachInfo = coachInfoMapper.selectCoachInfoByCourseId(1, courseId);
			}
			
			map.put("courseCount", orderDetail.getCourseCount() == null ? 1 : orderDetail.getCourseCount());
			map.put("payType",orderInfo.getPayType());
			map.put("orderType",orderInfo.getOrderType());
			// 正常
			if (bookStatus == OrderStatus.NORMAL.getIndex()) {
				map.put("orderId", orderInfo.getId());
				map.put("orderNumber", orderInfo.getOrderNumber());
				map.put("status", orderInfo.getOrderStatus());
				map.put("isCheckIn", 0);// TODO
				map.put("finishPeridos", orderInfo.getFinishPeridos());// TODO 已完成课时
				map.put("courseTime", courseTime);
				map.put("storeName", storeNamesb.toString());
				if (coachInfo != null) {
					map.put("coachName", coachInfo.getNickName());
					map.put("coachHeadImg", coachInfo.getHeadImg());
					map.put("coachMobile", coachInfo.getMobile());
				}
				if (courseInfo != null) {
					map.put("title", courseInfo.getTitle());
					map.put("courseId", courseInfo.getId());
					map.put("periods", (courseInfo.getPeriods()==0?orderDetail.getCourseCount():courseInfo.getPeriods()));// 课时
				}
			}

			// 预约排队
			if (bookStatus == OrderStatus.WAIT.getIndex()) {
				// 私课没有预约排队
			}

			// 已完成
			if (bookStatus == OrderStatus.FINISH.getIndex()) {
				map.put("title", courseInfo.getTitle());
				map.put("coachName", coachInfo.getNickName());
				map.put("storeName", storeNamesb);
				map.put("courseTime", time);
				map.put("coachId", coachInfo.getId());
				map.put("orderId", orderInfo.getId());
				map.put("coachHeadImg", coachInfo.getHeadImg());
			}

			// 已取消
			if (bookStatus == OrderStatus.FINISH.getIndex()) {
				map.put("title", courseInfo.getTitle());
				map.put("coachName", coachInfo.getNickName());
				map.put("storeName", storeNamesb);
				map.put("courseTime", time);
				map.put("coachId", coachInfo.getId());
				map.put("orderId", orderInfo.getId());
				map.put("coachHeadImg", coachInfo.getHeadImg());
			}

			mybooks.add(map);
		}
		return mybooks;
	}

	/**
	 * 获取已取消或已完成的预定
	 *
	 * @param bookStatus
	 * @return
	 */
	public List<Map<String, Object>> getMyFinishOrCancelBooks(int bookStatus, List<OrderInfo> orderList) {
		List<Map<String, Object>> mybooks = Lists.newArrayList();
		for (OrderInfo orderInfo : orderList) {
			Integer orderType = orderInfo.getOrderType();
			Integer serviceId = orderInfo.getServiceId();
			ServicePrice servicePrice = servicePriceMapper.selectByPrimaryKey(serviceId);
			Map<String, Object> map = new HashMap<String, Object>();
			OrderDetail orderDetail = orderDetailMapper.queryOrderDetailByOrderId(orderInfo.getId());
			StoreInfo storeInfo = null;
			if (orderDetail != null) {
				int storeId = orderDetail.getStoreId();
				storeInfo = storeInfoMapper.selectById(storeId);
				Resource resource1 = resourceMapper.queryResourceByStoreId(storeInfo.getId()).get(0);
				map.put("storeImg", resource1.getUrl());
			}
			map.put("orderType",orderInfo.getOrderType());
			map.put("updatedTime",DateUtils.format(orderInfo.getUpdatedTime(),DateUtils.dateTimePatternChinese));
			map.put("tradeId",orderInfo.getTradeId());
			// 自助健身
			if (orderInfo.getOrderType() == 4) {
				Date startTime = orderDetail.getStartTime();
				Date endTime = DateUtil.addMinites(startTime, orderDetail.getDuration());
				String courseTime = DateUtils.format(startTime, DateUtils.shortDatePattern) + " "
						+ DateUtils.format(startTime, DateUtils.shortTimePattern) + "～"
						+ DateUtils.format(endTime, DateUtils.shortTimePattern);
				map.put("title", "自助健身");
				map.put("orderType", orderInfo.getOrderType());
				map.put("coachName", "无");
				map.put("courseSchedule", courseTime);
				map.put("courseId", "");
				map.put("orderId", orderInfo.getId());
				map.put("orderNumber", orderInfo.getOrderNumber());
				map.put("coachHeadImg", "");
				map.put("storeName", storeInfo.getStoreName());
				mybooks.add(map);
				continue;
			}
			int courseId = servicePrice.getCourseId();
			CoachInfo coachInfo = coachInfoMapper.selectCoachInfoByCourseId(1, courseId);
//			CourseScheduleExample courseScheduleExample = new CourseScheduleExample();
//			courseScheduleExample.or().andCourseIdEqualTo(courseId);
//			List<CourseSchedule> scheduleList = courseScheduleMapper.selectByExample(courseScheduleExample);

            CourseSchedule courseScheduleDB = new CourseSchedule();
            courseScheduleDB.setCourseId(courseId);
            EntityWrapper<CourseSchedule> entityWrapper = new EntityWrapper<>(courseScheduleDB);
            List<CourseSchedule> scheduleList = courseScheduleMapper.selectList(entityWrapper);
			CourseSchedule courseSchedule = null;
			if (scheduleList.size() > 0) {
				courseSchedule = scheduleList.get(0);
			}
			map.put("orderId", orderInfo.getId());
			map.put("orderNumber", orderInfo.getOrderNumber());
			CourseInfo courseInfo = courseInfoMapper.selectById(courseId);
			if (courseInfo != null) {
				// 课程
				map.put("title", courseInfo.getTitle());
				map.put("courseId", courseInfo.getId());
			} else {
				// 自助健身
				map.put("title", servicePrice.getServiceName());
			}

			// 门店 todo:多门店情况
			if (storeInfo != null) {
				map.put("storeName", storeInfo.getStoreName());
			}

			// 教练
			if (coachInfo != null) {
				map.put("coachName", coachInfo.getNickName());
				map.put("coachHeadImg", coachInfo.getHeadImg());
			}

			// 课程时长 todo:趣味有多课程表
			String courseTime = "待与教练沟通确认";
			if (courseSchedule != null) {
				// 趣营
				if (CourseType.fun_camp.getType().equals(courseInfo.getCourseType())) {
					if (!Strings.isNullOrEmpty(courseSchedule.getWeekly())) {
						StringBuffer strWeekly = new StringBuffer("每周");
						String[] weekly = courseSchedule.getWeekly().split(",");
						for (String week : weekly) {
							strWeekly.append(DateUtil.numToUpper(Integer.parseInt(week)));
						}
						courseTime = DateUtil.formatDate(courseSchedule.getStartTime(), DateUtil.FMT_DATE_MMDD) + "至"
								+ DateUtil.formatDate(courseSchedule.getEndTime(), DateUtil.FMT_DATE_MMDD)
								+ strWeekly.toString();
					} else {
						courseTime = DateUtil.formatDate(courseSchedule.getStartTime(), DateUtil.FMT_DATE_MMDD) + "至"
								+ DateUtil.formatDate(courseSchedule.getEndTime(), DateUtil.FMT_DATE_MMDD);
					}
				} else {
					Date startTime = courseSchedule.getStartTime();
					Date endTime = DateUtil.addMinites(startTime, courseSchedule.getDuration());
					courseTime = DateUtils.format(startTime, DateUtils.shortDatePattern) + " "
							+ DateUtils.format(startTime, DateUtils.shortTimePattern) + "～"
							+ DateUtils.format(endTime, DateUtils.shortTimePattern);
				}
			}
			map.put("courseSchedule", courseTime);

			mybooks.add(map);
		}

		return mybooks;
	}

    /**
     * 查询课程订单数量 (檬营/私教/团课/自助健身)
     * @param orderStatus 订单状态
     * @param serviceType 服务类型
     * @param userId 用户ID
     * @param campType 檬营排队订单类型 1檬营未成营排队订单 2檬营爆仓排队订单
     * @return
     */
	@Override
	public int getMyBooksCount(int orderStatus, int serviceType, int userId, Integer campType) {
		if(serviceType == ServiceType.teamCourse.getIndex()){
			return orderInfoMapper.selectTeamCourseCount(orderStatus, serviceType, userId);
		}else if(serviceType == ServiceType.selfFitness.getIndex()){
			return orderInfoMapper.selectSelfFitnessCount(orderStatus, serviceType, userId);

		} else if (serviceType == ServiceType.campCourse.getIndex() && campType == null) {
			//檬营即将开始订单
			return orderInfoMapper.selectCamCourseCount(orderStatus, serviceType, userId, null);
		} else if (orderStatus == 3 && serviceType == ServiceType.campCourse.getIndex() && campType != null) {
			//檬营未成营排队/爆仓排队订单
			return orderInfoMapper.selectCamCourseCount(orderStatus, serviceType, userId, campType);
//		} else if (orderStatus == 3 && serviceType == ServiceType.campCourse.getIndex() && campType.intValue() == 2) {
//			//檬营爆仓排队订单
//			return orderInfoMapper.selectCamCourseCount(orderStatus, serviceType, userId, campType);

		}else if (serviceType == ServiceType.privateCourse.getIndex()) {
			//私教
			return orderInfoMapper.selectSecretCourseCount(orderStatus, serviceType, userId);
		} else {
			return orderInfoMapper.selectCountByOrderType(orderStatus, serviceType, userId);
		}
	}

	/**
	 * 获取订单详情
	 * 
	 * @param orderId
	 * @param userId
	 * @return
	 */
	public Map<String, Object> orderDetail(int orderId, int userId) throws OrderNotFoundException {
		Map<String, Object> map = new HashMap<String, Object>();
		OrderInfo orderInfo = orderInfoMapper.selectById(orderId);


		if (orderInfo != null) {
			// 获取订单信息

            map.put("orderStatus", orderInfo.getOrderStatus());
            map.put("totalPrice", orderInfo.getAmount());
            map.put("payStatus", orderInfo.getPayStatus());
            map.put("orderId", orderInfo.getId());
            map.put("orderType", orderInfo.getOrderType());

            // 获取订单详情
			OrderDetail orderDetail = orderDetailMapper.queryOrderDetailByOrderId(orderInfo.getId());;
			if (orderDetail == null) {
				map.put("msgData", "获取订单详情失败！联系管理员");
				logger.debug("获取订单详情失败！联系管理员");
				logger.error("====== 获取订单详情失败！联系管理员 =================");
			} 
			map.put("personCount", orderDetail.getPersonCount());
			if(orderInfo.getOrderType() == OrderContants.OrderType.physical_examination.getIndex()){
				map = queryPhysicalCouponOrderDetail(orderId, map);
			}else if(orderInfo.getOrderType() == OrderContants.OrderType.secret_experience.getIndex()){
				map = queryPrivatePhysicalOrderDetail(orderId, map);
			}else if(orderInfo.getOrderType() == OrderContants.OrderType.private_bespeak.getIndex()){
				map = queryPrivateBespeakOrderDetail(orderId, map);
			}else if (orderInfo.getOrderType() == 4) { // 自助健身
				// 开始时间
				Date startTime = orderDetail.getStartTime();
				String sectionTime = getDateType(startTime, orderDetail.getDuration(), "");


				map.putAll( accessService.updateAndGetNewQRCodeByOrderId(orderId));//门禁二维码
				map.put("sectionTime", sectionTime);
				// 店铺id
				// 获取门店信息
				ServicePrice servicePrice = servicePriceMapper.selectByPrimaryKey(orderInfo.getServiceId());
                Integer storeId = orderDetail.getStoreId();

//                StoreInfo storeInfo = storeInfoMapper.selectById(servicePrice.getStoreId());
                if (storeId != null && storeId > 0) {
                    StoreInfo storeInfo = storeInfoMapper.selectById(storeId);
                    Resource resourceS = resourceMapper.queryResourceByStoreId(storeInfo.getId()).get(0);
                    map.put("store_name", storeInfo.getStoreName());// 门店名字
                    map.put("notice", Arrays.asList(storeInfo.getNotice().split("\r\n")));// 注意事项
                    map.put("notice", storeInfo.getNotice().split("\r\n"));// 注意事项
                    map.put("longitude", storeInfo.getLongitude());// 经度
                    map.put("latitude", storeInfo.getLatitude());// 维度
                    map.put("storeId", storeInfo.getId());// 门店id
                    map.put("store_venues", storeInfo.getVenues());// 场地介绍
                    map.put("personCount", orderDetail.getPersonCount());
                    map.put("storeImg", resourceS.getUrl());
                    map.put("serviceName",servicePrice.getServiceName());
                }

			} else {
				ServicePrice servicePrice = servicePriceMapper.selectByPrimaryKey(orderInfo.getServiceId());
				// 课程信息
				CourseInfo courseInfo = courseInfoMapper.queryCourseInfoById(servicePrice.getCourseId());
				// 获取课程标题
				if (courseInfo != null) {
					map.put("title", courseInfo.getTitle());
					map.put("introduce", courseInfo.getIntroduce());
					map.put("course_headImg", courseInfo.getHeadImg());
					map.put("courseId", courseInfo.getId());
					map.put("serviceName",courseInfo.getTitle());
				}

                CourseSchedule courseScheduleDB = new CourseSchedule();
                courseScheduleDB.setCourseId(courseInfo.getId());
                EntityWrapper<CourseSchedule> entityWrapper = new EntityWrapper<>(courseScheduleDB);
                List<CourseSchedule> courseSchedules = courseScheduleMapper.selectList(entityWrapper);

				// 私教
				if (orderInfo.getOrderType() == 2) {
					map.put("sectionTime", "与教练联系确定时间");
					map.put("password", "课前请预先联系私教教练");
					map.put("boolPwd",false);
					map.put("courseCount", orderDetail.getCourseCount());
					map.put("mealCount", orderDetail.getMealCouponCount() == null ? 0 : orderDetail.getMealCouponCount());
				}
				// 檬营
				else if (orderInfo.getOrderType() == 3) {
					int beforeWaitNum = orderInfoMapper.queryBeforeWaitNum(orderInfo.getId(),orderInfo.getServiceId());

					map.put("sectionTime", courseInfo.getStartEndTime());
					//二维码
					map.putAll( accessService.updateAndGetNewQRCodeByOrderId(orderId));

					CourseSchedule courseSchedule = courseSchedules.get(0);
					if (courseSchedule !=null ) {
						//返回当前节时与 总课时
						CourseTime courseTime = orderInfoMapper.queryCourseStartTimeByOrderId(orderId);
//						//处理檬檬当前上课序号 教练签到销课逻辑 现在按当前上课时间逻辑处理
						int courseIndex = 0;
//						if (courseTime.getWeek() == null && ( courseTime.getWeekly().equals(0) || courseTime.getWeekly().equals(1) )) {
//							//第一节课还没开启签到 或 第一节课已开启签到 都返回第1节课
//							courseIndex = 1;
//						} else if (courseTime.getWeek() != null && courseTime.getWeekly().equals(0)) {
//							//已经签完了第1节课 后面的第N节课还没开启签到
//							courseIndex = courseTime.getWeek() + 1;
//						} else if (courseTime.getWeek() != null && courseTime.getWeekly().equals(1)) {
//							//已经签完了第1节课 后面的第N节课已开启签到
//							courseIndex = courseTime.getWeek();
//						}
						//直接按新的 来处理上课时间 不管教练是否已经签到

						if (courseTime != null && StringUtils.isNotBlank(courseTime.getCampClassTime())) {
							String[] campClassTime = courseTime.getCampClassTime().split(",");
							Date startTime = null;
							Date endTime = null;
							for (int i = 0; i < campClassTime.length; i++) {
								startTime = DateUtil.parseUtilDate(campClassTime[i], DateUtil.FMT_DATE_YYYYMMDDHHMM);
								endTime = DateUtil.addMinites(startTime, 90);
								if (new Date().before(endTime)) {
									courseIndex = i + 1;
									break;
								}
							}
							if (campClassTime.length > 0) {

								startTime = DateUtil.parseUtilDate(campClassTime[campClassTime.length - 1], DateUtil.FMT_DATE_YYYYMMDDHHMM);
								endTime = DateUtil.addMinites(startTime, 90);
								Date now = new Date();

								if (now.after(startTime) && now.before(endTime) || now.after(endTime)) {
									//当前时间在最后一节课中 || 已经结束也返回最后一节课
									courseIndex = campClassTime.length;
								}

							}
							map.put("courseNum", courseIndex);
							map.put("courseNumTotal", courseSchedules.get(0).getPeriods());
						}
					}
					map.put("maxCount", courseInfo.getMaxCount());
					map.put("minCount", courseInfo.getMinCount());
					map.put("waitCount", courseInfo.getWaitCount());
					map.put("currentCount", courseInfo.getCurrentCount());
					if(OrderContants.OrderStatus.WAIT.getStatus().equals(orderInfo.getOrderStatus())){
						map.put("yourWaitCount", beforeWaitNum+1);
					}else{
						map.put("yourWaitCount", 0);
					}

					map.put("boolPwd",false);
				}
				// 团课
				else if (orderInfo.getOrderType() == 1) {

					int beforeWaitNum = orderInfoMapper.queryBeforeWaitNum(orderInfo.getId(),orderInfo.getServiceId());
					String times = getDateType(courseSchedules.get(0).getStartTime(),
							courseSchedules.get(0).getDuration(), "");
					map.put("sectionTime", times);

					map.put("waitCount",beforeWaitNum);
					map.put("yourWaitCount", beforeWaitNum+1);
					map.putAll( accessService.updateAndGetNewQRCodeByOrderId(orderId));//门禁二维码

				}

				// 教练信息
				CoachInfo coachInfo = coachInfoMapper.selectCoachInfoByCourseId(1, courseInfo.getId());// 获取主教练
				if (coachInfo != null) {
					map.put("coachName", coachInfo.getNickName());
					map.put("headImg", coachInfo.getHeadImg());
					map.put("mobile",coachInfo.getMobile());
					map.put("QRCode", coachInfo.getWeixinQrCode()); //现在开始 二维码都通过教练表直接提供 blank May 5 2017

				}
				// 获取门店信息
                CourseStore courseStoreDB = new CourseStore();
                courseStoreDB.setCourseId(courseInfo.getId());
                EntityWrapper entityWrapper2 = new EntityWrapper<>(courseStoreDB);
                List<CourseStore> listCS = courseStoreMapper.selectList(entityWrapper2);

				String sName = "";
				// 私教返回的经纬度为 0
				Resource resourceS = null;
				if (orderInfo.getOrderType() == 2) {
					if (listCS.size() > 0) {
						for (CourseStore cs : listCS) {
							StoreInfo storeInfo = storeInfoMapper.selectById(cs.getStoreId());
							if(sName.length() == 0) {
								sName = sName + storeInfo.getStoreName();
							}else {
								sName = sName +"、"+ storeInfo.getStoreName();
							}
							
						}
					}
					
				} else {
					StoreInfo storeInfo = storeInfoMapper.selectById(listCS.get(0).getStoreId());
					sName = storeInfo.getStoreName();
				}
				StoreInfo storeInfo = storeInfoMapper.selectById(listCS.get(0).getStoreId());
				resourceS = resourceMapper.queryResourceByStoreId(storeInfo.getId()).get(0);
				map.put("store_name", sName);// 门店名字
				map.put("notice", Arrays.asList(storeInfo.getNotice().split("\r\n")));// 注意事项
				map.put("notice", storeInfo.getNotice().split("\r\n"));// 注意事项
				map.put("longitude", storeInfo.getLongitude());// 经度
				map.put("latitude",storeInfo.getLatitude());// 维度
				map.put("storeId", storeInfo.getId());// 门店id
				map.put("store_venues", storeInfo.getVenues());// 场地介绍
				map.put("storeImg", resourceS.getUrl());

			}

		}
		return map;
	}

	/**
	 * 获取时间格式
	 * 
	 * @param date
	 * @param duration
	 * @param type
	 * @return
	 */
	public String getDateType(Date date, int duration, String type) {
		String dateStr = DateUtils.format(date, DateUtils.datePattern);
		Date endTime = DateUtil.addMinites(date, duration);
		String courseTime = DateUtils.format(date, DateUtils.datePatternAllHH);
		String sectionTime = (DateUtils.format(date, DateUtils.shortDatePattern)).replaceAll("-", ".") + " "
				+ DateUtils.getWeekDay(dateStr) + " " + DateUtils.format(date, DateUtils.shortTimePattern) + "-"
				+ DateUtils.format(endTime, DateUtils.shortTimePattern);

		return sectionTime;
	}

	/**
	 * 返回密码提示文字
	 * 
	 * @param date  订单开始时间
	 * @param pwd 	门禁密码
	 * @return      密码或提示文字
	 */
	public String getPwdStatusWord(Date date, String pwd, OrderInfo orderInfo) {
        if ("3".equals(orderInfo.getOrderStatus())) {
            return "你当前正处于排队状态";
        } else if ("2".equals(orderInfo.getOrderStatus())) {
            return "你已成功取消订单";
        } else if ("4".equals(orderInfo.getOrderStatus())) {
            return "您的订单已完成";
        }
        if (date == null) {
            return "订单存在异常请于客服联系";
        }

        Date nowDate = new Date();
        Date now_30 = new Date(date.getTime() - 20 * 60000); // 20分钟前的时间
        String courseTime = DateUtils.format(date, DateUtils.datePatternAllHH);
        String msg;
        if (nowDate.after(now_30)) {
            msg = pwd;
        } else {
            msg = "将于" + (DateUtils.format(date, DateUtils.shortDatePattern)).replaceAll("-", ".") + " "
                    + DateUtils.getWeekDay(courseTime) + " " + DateUtils.format(now_30, DateUtils.shortTimePattern)
                    + "显示";
        }

        return msg;
    }

	/**
	 * 计算两个时间相差的天数
	 * 
	 * @param smdate
	 * @param bdate
	 * @return
	 * @throws ParseException
	 */
	public static int daysBetween(Date smdate, Date bdate) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		smdate = sdf.parse(sdf.format(smdate));
		bdate = sdf.parse(sdf.format(bdate));
		Calendar cal = Calendar.getInstance();
		cal.setTime(smdate);
		long time1 = cal.getTimeInMillis();
		cal.setTime(bdate);
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);

		return Integer.parseInt(String.valueOf(between_days));
	}
	
	/**
	 * 获取团课的订单
	 */
	@Override
	public List<Map<String, Object>> getTeamCourseCount(int orderStatus, int serviceType, int userId) {
	
		return null;
	}
	
	/**
	 * 获取分享朋友圈的签名
	 */
	@Override
	public ApiResultModel getSing(String URL, String invalid) {
		TenWeChatGenerator  tg = new TenWeChatGenerator();
		Token token = tokenRedisDao.queryTokenByRedis();
    	Map<String,Object> map = new HashMap<String,Object>();
    	Map<String,String> maps = new HashMap<String,String>();
    	maps = tg.getNewSing(URL,token.getToken());
    	maps.put("appId",String.valueOf(PropertiesUtil.get("wechat_appid")).trim());
    	ApiResultModel<Map<String, String>> apiResultModel = new ApiResultModel<Map<String, String>>();
    	apiResultModel.setData(maps);
    	apiResultModel.setLogined(true);
    	apiResultModel.setMsg("获取签名");
    	apiResultModel.setRet(0);
    	return apiResultModel;
	}
	
	public String getOrderType(int type){
		String OrderType = "";
		switch (type) {
		case 1: OrderType = "团体订单";
			break;
		case 2: OrderType = "私教订单";
		break;
		case 3: OrderType = "檬营订单";
		break;
		case 4: OrderType = "自助订单";
		break;
		}
		return OrderType;
	}
	
	/**
	 * 获取已完成 和取消的全部订单列表
	 * @param bookStatus
	 * @param orderList
	 * @return
	 */
	public List<Map<String, Object>> getMyFinishOrCancelBooksNew(int bookStatus, List<OrderInfo> orderList){
		List<Map<String, Object>> mybooks = Lists.newArrayList();
		for (OrderInfo orderInfo : orderList) {
			Integer orderType = orderInfo.getOrderType();
			Integer serviceId = orderInfo.getServiceId();
			String headImg = "";
			String startTime = "";
			String title = "";
			String name ="";
			String nickName ="";
			ServicePrice servicePrice = servicePriceMapper.selectByPrimaryKey(serviceId);
			Map<String, Object> map = new HashMap<String, Object>();
			OrderDetail orderDetail = orderDetailMapper.queryOrderDetailByOrderId(orderInfo.getId());
				StoreInfo storeInfo = storeInfoMapper.selectById(servicePrice.getStoreId());
			map.put("orderId", orderInfo.getId());
			map.put("orderNumber", orderInfo.getOrderNumber());
			map.put("tradeId", orderInfo.getTradeId());
			// 2017-04-08 13：07 修改 因为 出现了执行脚本的时候将所有的update_time 修改为同一天
			//String update_time  =  orderInfo.getUpdatedTime()==null?DateUtils.format(new Date(), DateUtils.dateTimePatternChinese):DateUtils.format(orderInfo.getUpdatedTime(), DateUtils.dateTimePatternChinese);
			String update_time  =  null;
			// 如果是用户取消订单的话就用取消时间来	
			if(OrderContants.OrderStatus.CANCEL.equals(orderInfo.getOrderStatus())){
				update_time = orderInfo.getUserCancelTime()==null?DateUtils.format(orderInfo.getCreatedTime(), DateUtils.dateTimePatternChinese):DateUtils.format(orderInfo.getUserCancelTime(), DateUtils.dateTimePatternChinese);
			}else{
			// 订单已完成使用 用户的创建订单时间来排序
				update_time = orderInfo.getCreatedTime()==null?DateUtils.format(new Date(), DateUtils.dateTimePatternChinese):DateUtils.format(orderInfo.getCreatedTime(), DateUtils.dateTimePatternChinese);
			}
			map.put("updateTime", update_time);
			map.put("orderType", orderInfo.getOrderType());
			map.put("storeId",storeInfo == null ?"":storeInfo.getId());
			map.put("storeName",storeInfo == null ?"":storeInfo.getStoreName());
			map.put("payType",orderInfo.getPayType() == 2 ? 2 : 1);
			
			// 门店
			
			ResourceExample resourceE  = new ResourceExample();
			// 自助健身不需要教练头像
			if(orderInfo.getOrderType() == 4){
				if(storeInfo != null){
					resourceE.or().andParentIdEqualTo(storeInfo.getId()).andParentTypeEqualTo("1").andResTypeEqualTo("1");
					startTime = formatDateToString(orderDetail.getStartTime(),null,orderDetail.getDuration(),orderInfo.getOrderType());
					List<Resource> resourceList =  resourceMapper.selectByExample(resourceE);
					Resource  resource = resourceList.get(0);
					headImg = resource.getUrl();
					title = "自助健身";
					nickName = "无";
					name = storeInfo.getStoreName();
				}
			}else{
				CoachInfo coachInfo = null;
				if(orderInfo.getOrderType() == OrderContants.OrderType.physical_examination.getIndex() 
					|| orderInfo.getOrderType() == OrderContants.OrderType.secret_experience.getIndex()){
					coachInfo = coachInfoMapper.selectById(orderDetail.getCoachId());
				}else{
					coachInfo = coachInfoMapper.selectCoachInfoByCourseId(1, servicePrice.getCourseId());
				}
				
//				CourseScheduleExample courseScheduleExample = new CourseScheduleExample();
//				courseScheduleExample.or().andCourseIdEqualTo(servicePrice.getCourseId());
//				List<CourseSchedule> scheduleList = courseScheduleMapper.selectByExample(courseScheduleExample);

                CourseSchedule courseScheduleDB = new CourseSchedule();
                courseScheduleDB.setCourseId(servicePrice.getCourseId());
                EntityWrapper<CourseSchedule> entityWrapper = new EntityWrapper<>(courseScheduleDB);
                List<CourseSchedule> scheduleList = courseScheduleMapper.selectList(entityWrapper);

				CourseSchedule courseSchedule = null;//
				/*CourseInfo courseInfo = courseInfoMapper.selectByPrimaryKey(servicePrice.getCourseId());*/
				CourseInfo courseInfo = courseInfoMapper.queryCourseInfoById(servicePrice.getCourseId());
				// 体测 体验  私教 的开始结束时间按照销课的时间来
				if(orderInfo.getOrderType().intValue() == OrderContants.OrderType.pt.getIndex() 
						|| OrderContants.OrderType.physical_examination.getIndex() == orderInfo.getOrderType().intValue()
						|| OrderContants.OrderType.secret_experience.getIndex() == orderInfo.getOrderType().intValue()){
					startTime = courseSignMapper.getPtCourseStartTimeAndEndTimeByOrderId(orderInfo.getId());
					
				}else{
					if(scheduleList.size() > 0){
						courseSchedule = scheduleList.get(0);
						int  duration =  courseSchedule.getDuration()==null?0:courseSchedule.getDuration();
						startTime = formatDateToString(courseSchedule.getStartTime(),courseSchedule.getEndTime(),duration,orderInfo.getOrderType());
					}
				}
				//resourceE.or().andParentIdEqualTo(servicePrice.getCourseId()).andParentTypeEqualTo("2").andResKeyEqualTo("1");
				// 获取开始时间
				if(coachInfo != null){
					nickName = coachInfo.getNickName();
					headImg = coachInfo.getHeadImg();
					title = courseInfo.getTitle();
					name = coachInfo.getNickName();
				}
			}
			
			
			map.put("name",name);
			map.put("startTime",startTime);
			map.put("headImg",headImg);
			map.put("title", title);
			map.put("nickName",nickName);
			map.put("courseCount",orderDetail.getCourseCount());
			mybooks.add(map);
		}
		return mybooks;
	}  
	
	public String formatDateToString(Date date_s,Date date_e, int duration,int type){
		Date startTime = date_s;
		String courseTime = null;
		Date endTime = null;
		if(type == 1 || type == 4){
			endTime = DateUtil.addMinites(date_s,duration);
			courseTime = DateUtils.format(startTime, DateUtils.shortDatePattern) + " "
					+ DateUtils.format(startTime, DateUtils.shortTimePattern) + "～"
					+ DateUtils.format(endTime, DateUtils.shortTimePattern);
		}else if(type == 3){
			courseTime =DateUtils.format(date_s, DateUtils.shortDatePattern) +"～"+DateUtils.format(date_e, DateUtils.shortDatePattern);
		}
		
		
		return courseTime;
	}
	
	/**
	 * 预约订单返回订单详情
	 * @param orderId
	 * @param parmasMap
	 * @return
	 */
	public Map<String,Object> queryPrivateBespeakOrderDetail(Integer orderId,Map<String,Object> parmasMap){
		parmasMap = orderDetailMapper.queryOrderDetailMapByOrderId(orderId);
		String notice = (String) parmasMap.get("notice");
		parmasMap.put("notice", Arrays.asList(notice.split("\r\n")));// 注意事项
		parmasMap.put("prompt", "将在24小时内与您联系");
		return  parmasMap;
	}
	
	/**
	 * 私教订单返回订单详情
	 * @param orderId
	 * @param parmasMap
	 * @return
	 */
	public Map<String,Object> queryPrivatePhysicalOrderDetail(Integer orderId,Map<String,Object> parmasMap){
		parmasMap = orderDetailMapper.queryOrderDetailMapByOrderId(orderId);
		String notice = (String) parmasMap.get("notice");
		parmasMap.put("notice", Arrays.asList(notice.split("\r\n")));// 注意事项
		parmasMap.put("prompt", "教练将在1天内与您联系确定上课时间");
		return  parmasMap;
	}
	
	/**
	 * 体测订单返回订单详情
	 * @param orderId
	 * @param parmasMap
	 * @return
	 */
	public Map<String,Object> queryPhysicalCouponOrderDetail(Integer orderId,Map<String,Object> parmasMap){
		parmasMap = orderDetailMapper.queryOrderDetailMapByOrderId(orderId);
		String notice = (String) parmasMap.get("notice");
		parmasMap.put("notice", Arrays.asList(notice.split("\r\n")));// 注意事项
		parmasMap.put("prompt", "教练将在1天内与您联系确定体测时间");
		return  parmasMap;
	}

	/**
	 * 获取用户私教咨询订单列表详情
	 */
	public Map<String, Object> queryUserPrivateConsultOrderDetailListByUserId(Integer userId) {
		// TODO Auto-generated method stub
		Map<String,Object> resultMap = new HashMap<>();
		List<PrivateConsultOrderApiModel> consultOrderList = orderDetailMapper.queryUserPrivateConsultOrderListByUserId(userId);
		resultMap.put("consultOrderList", consultOrderList);
		return resultMap;
	}
	

}
